<template>
	<view class="tab-bar-warp flex-x-around">
		<view @click="handleSwitch(i)" v-for="(item,i) in list" :key="item.name" :class="{'tab-bar-item gray': true, 'checked bold': i===lifeCircleCurrentTabbar}">
			<view class="text">{{ item.name }}</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import {
		getSigGroup
	} from '../../../apis/life-circle';

	export default {
		data() {
			return {
				list: [{
						index: 0,
						pagePath: "/pages/life-circle",
						name: "组局"
					},
					{
						index: 1,
						pagePath: "/pages/life-circle/group-chat/index",
						name: "圈聊"
					},
					{
						index: 2,
						pagePath: "/pages/life-circle/message/index",
						name: "消息"
					}
				]
			};
		},
		computed: {
			...mapGetters(["lifeCircleCurrentTabbar", "myTimInfo", "openId"])
		},
		onReady() {
			uni.getStorageSync("userSigGroup") ? this.timlogin() : this.getUserSigGroup();
		},
		methods: {
			getUserSigGroup() {
				this.$loading.show()
				const params = {
					openid: uni.getStorageSync("openId"),
					name: uni.getStorageSync("userInfo").nickName,
					portrait: uni.getStorageSync("userInfo").avatarUrl
				}

				getSigGroup(params).then(res => {
					uni.setStorageSync("userSigGroup", res.data.im_token_zuju);
					this.$loading.hide();
					this.timlogin()
				})
			},
			timlogin() {
				const userID = this.openId + '_group',
					userSig = uni.getStorageSync("userSigGroup");
 				// case1: 要登录的用户是当前已登录的用户，则直接跳转即可
				if (this.myTimInfo.userID && userID === this.myTimInfo.userID) return;

				// case2: 当前已经登录了用户，但是和即将登录的用户不一致，则先登出当前登录的用户，再登录
				if (this.myTimInfo.userID) {
					this.$store.dispatch("tim/resetStore");
					uni.$Tim.logout().then(() => {
						this.login(userID, userSig);
					});
					return;
				}
				// case3: 正常登录流程
				this.login(userID, userSig);
			},
			login(userID, userSig) {
				try{
					uni.$Tim.login({userID,userSig})
				}catch(e){
					console.log("tim登录失败!!!");
					//TODO handle the exception
				}
			},
			handleSwitch(i) {
				if (this.list[i] === this.lifeCircleCurrentTabbar) return;

				let url = this.list[i].pagePath;

				this.$store.dispatch("life-circle/setCurrentTabbar", i);

				if (url === "/pages/life-circle") {
					return uni.switchTab({
						url
					});
				}
				uni.navigateTo({
					url
				});
			}
		}
	};
</script>

<style lang="less">
	.tab-bar-warp {
		width: 60%;
		// display: flex;
		// flex-direction: row;
		// align-items: center;
		// justify-content: space-around;
	}

	.tab-bar-item.checked {
		font-size: 34rpx;
		font-family: Source Han Sans CN;
		color: rgba(51, 51, 51, 1);
	}
</style>
